import { OrderType } from '@/enums'
import {
  cancelOrder,
  deleteOrder,
  FollowOrUnfollow,
  getPrescriptionPic
} from '@/services/consul'
import { getMedicalOrderDetail } from '@/services/order'
import type { ConsultOrderItem, FollowType } from '@/types/consult'
import type { OrderDetail } from '@/types/order'
import { showFailToast, showImagePreview, showSuccessToast } from 'vant'
import { onMounted, ref } from 'vue'

export const useFollow = (type: FollowType = 'doc') => {
  // 1. 按钮状态 - 加载中
  // 2. 更新按钮文本 - 已关注 or 未关注
  // 3. 关注成功or关注失败(网络原因) 需要将按钮的loading状态改为false

  const loading = ref(false)
  const follow = async (item: { id: string; likeFlag: 0 | 1 }) => {
    loading.value = true
    try {
      await FollowOrUnfollow(item.id)
      item.likeFlag = item.likeFlag === 1 ? 0 : 1
    } finally {
      loading.value = false
    }
  }
  return { loading, follow }
}

// 查看处方
export const usePrescriptionPic = () => {
  const showPrescriptionPic = async (id?: string) => {
    if (id) {
      const res = await getPrescriptionPic(id)
      showImagePreview([res.data.url])
    }
  }
  return { showPrescriptionPic }
}

// 取消订单
export const useCancelConsultOrder = () => {
  const loading = ref(false)
  const cancelConsultOrder = async (item: ConsultOrderItem) => {
    loading.value = true
    try {
      await cancelOrder(item.id)
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'
      showSuccessToast('取消成功')
    } catch (error) {
      showFailToast('取消失败')
    } finally {
      loading.value = false
    }
  }
  return { loading, cancelConsultOrder }
}
// 删除订单
export const useDeleteOrder = (callback?: () => void) => {
  const loading = ref(false)
  const onDelete = async (item: ConsultOrderItem) => {
    loading.value = true
    try {
      await deleteOrder(item.id)

      // 如果有回调函数
      callback && callback()
      showSuccessToast('删除成功')
    } catch (error) {
      showFailToast('删除失败')
    } finally {
      loading.value = false
    }
  }
  return { loading, onDelete }
}

// 获取药品订单详情

export const useOrderDetail = (id: string) => {
  const orderDetail = ref<OrderDetail>()
  const loading = ref(false)
  const loadOrderDetail = async () => {
    try {
      loading.value = true
      const res = await getMedicalOrderDetail(id)
      orderDetail.value = res.data
    } finally {
      loading.value = false
    }
  }
  onMounted(() => {
    loadOrderDetail()
  })
  return { loading, orderDetail }
}

// 类型兼容
// type SObj = {
//   age: number
//   name: string
// }
// const obj = {
//   name: 'qee',
//   age: 18,
//   gender: 'nv'
// }
// const nObj = {
//   age: 18
// }
// const getUser = (obj: SObj) => {
//   console.log(obj)
// }
// getUser(obj) //只关注自己本身的，以外的不关注yhb
// getUser(nObj) //少的不能传多的
